package cn.uyunsky.platform.service.impl;

import cn.uyunsky.platform.data.UDataTool;
import cn.uyunsky.platform.data.UData;
import cn.uyunsky.platform.entity.impl.PlRole;
import cn.uyunsky.platform.entity.impl.PlUser;
import cn.uyunsky.platform.exception.PLException;
import cn.uyunsky.platform.service.IServiceAbstract;
import cn.uyunsky.platform.util.PL;
import org.apache.commons.lang.StringUtils;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: baiyh
 * Date: 13-6-15
 * Time: 下午3:45
 */
@Service(value = "LoginService")
@Transactional
public class LoginService extends IServiceAbstract {

    private HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

    @Override
    public UData doService(UData data) throws PLException {
        String userid = (String) data.getBody().get("userid");
        String password = (String) data.getBody().get("password");

        if (StringUtils.isBlank(userid) || StringUtils.isBlank(password)) {
            throw new PLException("");//TODO
        } else {
            password = PL.md5encode(password);
        }

        //TODO 停用状态
        String hql = "from cn.uyunsky.platform.entity.impl.PlUser s where s.userid = :userid and s.password = :password";
        String[] params = {"userid", "password"};
        Object[] values = {userid, password};
        List list = hibernateTemplate.findByNamedParam(hql, params, values);
        if (list.size() <= 0) {
            throw new PLException("");//TODO
        } else {
            PlUser plUser = (PlUser) list.get(0);
            Map resdata = new HashMap();
            resdata.put("userid", userid);
            resdata.put("username", plUser.getUsername());
            PlRole role = plUser.getRole();
            resdata.put("roleid", role == null ? "" : role.getId());
            return UDataTool.createSuccessResult(resdata);
        }
    }
}
